package com.getpebble.android.framework.endpoint;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.os.Handler;
import android.os.Looper;
import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.model.PblInstalledAppDataModel;
import com.getpebble.android.framework.app.InstalledApp;
import com.getpebble.android.framework.app.InstalledApp.AppCompanyVersionTuple;
import com.getpebble.android.framework.endpoint.EndpointRequest.EndpointAction;
import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.framework.protocol.inbound.PblInboundAppBankInfoInstallMessage;
import com.getpebble.android.framework.protocol.inbound.PblInboundAppBankInfoInstallMessage.BankInfoEntry;
import com.getpebble.android.framework.protocol.inbound.PblInboundAppInfoInstallMessage;
import com.getpebble.android.framework.protocol.inbound.PblInboundAppInstallMessage;
import com.getpebble.android.framework.protocol.inbound.PblInboundAppInstallMessage.AppInstallResponseType;
import com.getpebble.android.framework.protocol.inbound.PblInboundAppListInstallMessage;
import com.getpebble.android.framework.protocol.outbound.PblOutboundAppInstallMessage;
import com.getpebble.android.jskit.bridge.InstalledAppsBridge;
import com.google.common.collect.ImmutableSet;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class FetchAppsEndpoint extends RequestableEndpoint {
    private static final String TAG = FetchAppsEndpoint.class.getSimpleName();
    private Context mContext;
    private Handler mHandler;
    private Set<UUID> mKnownAppUuids;
    private Listener mListener;
    private IEndpointMessageSender mMessageSender;
    private Map<AppCompanyVersionTuple, InstalledApp> mNeedInsertApps;
    private Runnable mTimeoutRunnable;
    private List<UUID> mUnknownAppUuids;

    static /* synthetic */ class AnonymousClass2 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction = new int[EndpointAction.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundAppInstallMessage$AppInstallResponseType = new int[AppInstallResponseType.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction[EndpointAction.GET_APP_BANK_INFO.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundAppInstallMessage$AppInstallResponseType[AppInstallResponseType.APP_BANK_INFO.ordinal()] = 1;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundAppInstallMessage$AppInstallResponseType[AppInstallResponseType.APP_LIST.ordinal()] = 2;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundAppInstallMessage$AppInstallResponseType[AppInstallResponseType.APP_INFO.ordinal()] = 3;
            } catch (NoSuchFieldError e4) {
            }
        }
    }

    interface Listener {
        void onAppsFetchComplete(boolean z);
    }

    public FetchAppsEndpoint(Context context, IEndpointMessageSender messageSender, Listener listener) {
        this.mTimeoutRunnable = new Runnable() {
            public void run() {
                Trace.warning(FetchAppsEndpoint.TAG, "Timeout");
                if (FetchAppsEndpoint.this.mListener != null) {
                    FetchAppsEndpoint.this.mListener.onAppsFetchComplete(false);
                }
            }
        };
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        } else if (messageSender == null) {
            throw new IllegalArgumentException("'messageSender' cannot be null!");
        } else {
            this.mContext = context;
            this.mMessageSender = messageSender;
            this.mListener = listener;
            this.mNeedInsertApps = Collections.EMPTY_MAP;
            this.mUnknownAppUuids = Collections.EMPTY_LIST;
            this.mKnownAppUuids = Collections.EMPTY_SET;
            this.mHandler = new Handler(Looper.getMainLooper());
        }
    }

    public FetchAppsEndpoint(Context context, IEndpointMessageSender messageSender) {
        this(context, messageSender, null);
    }

    Set<EndpointId> getSupportedEndpoints() {
        return ImmutableSet.of(EndpointId.APP_INSTALL_MANAGER);
    }

    private void startTimeout() {
        this.mHandler.postDelayed(this.mTimeoutRunnable, 5000);
    }

    private void cancelTimeout() {
        this.mHandler.removeCallbacks(this.mTimeoutRunnable);
    }

    boolean onReceive(ProtocolMessage message) {
        boolean handled = false;
        Trace.debug(TAG, "Got protocol message");
        PblInboundAppInstallMessage appMessage = PblInboundAppInstallMessage.createMessage(message);
        if (appMessage == null) {
            Trace.debug(TAG, "AppMessage is null");
            return false;
        }
        cancelTimeout();
        switch (AnonymousClass2.$SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundAppInstallMessage$AppInstallResponseType[appMessage.getResponseType().ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                updateAppBankInfo((PblInboundAppBankInfoInstallMessage) appMessage);
                handled = true;
                break;
            case SMTPMessage.RETURN_HDRS /*2*/:
                updateUuidList((PblInboundAppListInstallMessage) appMessage);
                handled = true;
                break;
            case ListInfo.INDETERMINATE /*3*/:
                updateAppInfo((PblInboundAppInfoInstallMessage) appMessage);
                handled = true;
                break;
        }
        return handled;
    }

    private ContentResolver getContentResolver() {
        return this.mContext.getContentResolver();
    }

    private IEndpointMessageSender getMessageSender() {
        return this.mMessageSender;
    }

    private PblDevice getDevice() {
        return getMessageSender().getDevice();
    }

    private void updateAppBankInfo(PblInboundAppBankInfoInstallMessage appMessage) {
        Trace.debug(TAG, "Updating the bank info");
        Map<AppCompanyVersionTuple, InstalledApp> cachedAppMap = fetchCachedAppMap();
        Map<AppCompanyVersionTuple, BankInfoEntry> entryMap = getEntryMap(appMessage.getEntryList());
        List<Integer> appIdsToDelete = getAppsToDelete(cachedAppMap, entryMap);
        this.mNeedInsertApps = new HashMap();
        this.mKnownAppUuids = new HashSet();
        List<ContentValues> needUpdateRows = new ArrayList();
        for (AppCompanyVersionTuple tuple : entryMap.keySet()) {
            InstalledApp entryApp = (InstalledApp) cachedAppMap.get(tuple);
            BankInfoEntry bankInfoEntry = (BankInfoEntry) entryMap.get(tuple);
            if (entryApp == null) {
                this.mNeedInsertApps.put(tuple, InstalledApp.fromBankInfoEntry(bankInfoEntry, getDevice().getAddress()));
                Trace.debug(TAG, "Adding insert app for: " + bankInfoEntry.getAppName());
            } else if (entryApp.needsUpdateFrom(bankInfoEntry)) {
                entryApp.updateFrom(bankInfoEntry);
                needUpdateRows.add(entryApp.toContentValues());
                this.mKnownAppUuids.add(entryApp.getUuid());
                Trace.debug(TAG, "Adding update app for: " + bankInfoEntry.getAppName());
            } else {
                this.mKnownAppUuids.add(entryApp.getUuid());
                Trace.debug(TAG, "No update needed for: " + bankInfoEntry.getAppName());
            }
        }
        PblInstalledAppDataModel.deleteApps(getContentResolver(), appIdsToDelete);
        PblInstalledAppDataModel.updateApps(getContentResolver(), needUpdateRows);
        if (!this.mNeedInsertApps.isEmpty()) {
            requestUuidList();
        } else if (this.mListener != null) {
            this.mListener.onAppsFetchComplete(true);
        }
    }

    private void updateUuidList(PblInboundAppListInstallMessage message) {
        Trace.debug(TAG, "Got the list of uuids");
        List<UUID> allUuids = message.getAppUuidList();
        this.mUnknownAppUuids = new ArrayList();
        for (UUID uuid : allUuids) {
            if (!this.mKnownAppUuids.contains(uuid)) {
                this.mUnknownAppUuids.add(uuid);
            }
        }
        requestNextUuid();
    }

    private void updateAppInfo(PblInboundAppInfoInstallMessage message) {
        if (this.mUnknownAppUuids.isEmpty()) {
            Trace.error(TAG, "Got app info for unknown UUID");
            return;
        }
        UUID requestedUUID = (UUID) this.mUnknownAppUuids.remove(0);
        InstalledApp installedApp = (InstalledApp) this.mNeedInsertApps.remove(new AppCompanyVersionTuple(message.getAppName(), message.getCompanyName(), message.getVersion()));
        if (installedApp == null) {
            Trace.error(TAG, "Unable to find matching app for " + requestedUUID + " from " + message.getAppName());
            requestNextUuid();
            return;
        }
        installedApp.setUuid(requestedUUID);
        String[] capabilities = InstalledAppsBridge.getInstance(this.mContext).getCapabilitiesForApp(requestedUUID);
        if (capabilities != null && capabilities.length > 0) {
            installedApp.setCapabilities(capabilities);
        }
        PblInstalledAppDataModel.insertApp(getContentResolver(), installedApp.toContentValues());
        requestNextUuid();
    }

    private void requestUuidList() {
        Trace.debug(TAG, "Requesting full UUID list");
        getMessageSender().sendMessage(PblOutboundAppInstallMessage.createGetList());
        startTimeout();
    }

    private void requestNextUuid() {
        if (!this.mUnknownAppUuids.isEmpty()) {
            UUID uuidToRequest = (UUID) this.mUnknownAppUuids.get(0);
            Trace.debug(TAG, "Requesting " + uuidToRequest);
            getMessageSender().sendMessage(PblOutboundAppInstallMessage.createGetAppInfo(uuidToRequest));
            startTimeout();
        } else if (this.mListener != null) {
            this.mListener.onAppsFetchComplete(true);
        }
    }

    private List<Integer> getAppsToDelete(Map<AppCompanyVersionTuple, InstalledApp> cachedAppMap, Map<AppCompanyVersionTuple, BankInfoEntry> entryMap) {
        List<Integer> appIdsToDelete = new ArrayList();
        for (AppCompanyVersionTuple tuple : cachedAppMap.keySet()) {
            if (!entryMap.containsKey(tuple)) {
                appIdsToDelete.add(((InstalledApp) cachedAppMap.get(tuple)).getId());
            }
        }
        return appIdsToDelete;
    }

    private Map<AppCompanyVersionTuple, BankInfoEntry> getEntryMap(List<BankInfoEntry> entryList) {
        Map<AppCompanyVersionTuple, BankInfoEntry> entryMap = new HashMap();
        for (BankInfoEntry entry : entryList) {
            entryMap.put(new AppCompanyVersionTuple(entry.getAppName(), entry.getCompanyName(), entry.getVersionNumber()), entry);
        }
        return entryMap;
    }

    private Map<AppCompanyVersionTuple, InstalledApp> fetchCachedAppMap() {
        Map<AppCompanyVersionTuple, InstalledApp> cachedAppMap = new HashMap();
        Cursor cachedAppsCursor = PblInstalledAppDataModel.fetchInstalledApps(getContentResolver(), getDevice());
        while (cachedAppsCursor != null && cachedAppsCursor.moveToNext()) {
            ContentValues contentValues = new ContentValues();
            DatabaseUtils.cursorRowToContentValues(cachedAppsCursor, contentValues);
            InstalledApp installedApp = InstalledApp.fromContentValues(contentValues);
            cachedAppMap.put(installedApp.getTuple(), installedApp);
        }
        if (cachedAppsCursor != null) {
            cachedAppsCursor.close();
        }
        return cachedAppMap;
    }

    boolean onRequest(EndpointRequest request, FrameworkState frameworkState) {
        Trace.debug(TAG, "Got request");
        boolean supported = false;
        PblOutboundAppInstallMessage message = null;
        switch (AnonymousClass2.$SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction[request.getAction().ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                Trace.debug(TAG, "Getting bank info");
                message = PblOutboundAppInstallMessage.createGetBankInfo();
                supported = true;
                break;
        }
        if (message != null) {
            getMessageSender().sendMessage(message);
            startTimeout();
        }
        return supported;
    }

    boolean onPrfRequest(EndpointRequest request, FrameworkState frameworkState) {
        boolean supported = false;
        if (request.getAction().equals(EndpointAction.GET_APP_BANK_INFO)) {
            supported = true;
            if (this.mListener != null) {
                this.mListener.onAppsFetchComplete(false);
            }
        }
        Trace.debug(TAG, "Is request supported? " + supported);
        return supported;
    }
}
